<template>
	<div class="index-login p-b-70 propay">
		<!-- 初始空白 -->
		<div v-if="loading"></div>
		<!-- 授权加载 -->
		<div v-else>
			<div class="main" :style="'background:'+ colorList[0]">
				<img :src="baseUrl+ imagesList[0]" />

				<div id="form"></div>
				<el-form :model="form" :rules="rules" ref="form">
					<el-form-item  prop="mobile">
						<div class="df">
							<el-input v-model.number="form.mobile" placeholder="请输入手机号" @input="handlePhone">
								<span slot="prefix">+86</span>
							</el-input>
							<div class="el-form-item__error" v-if="showError">{{showText}}</div>
						</div>
					</el-form-item>
					<el-form-item  prop="code">
						<el-input v-model="form.code" placeholder="请输入验证码" @input="handleSms" class="sms">
							<el-button @click="getCode" :disabled="timer"  slot="suffix" :style="'background:' + colorList[1] + ';border-color:' + colorList[1]"> {{ timer ? `${count}秒后重新获取` : '获取验证码' }}</el-button>
						</el-input>
					</el-form-item>
				</el-form>
				<div class="cbtn" @click="submitForm('form',0)" :style="'background:'+ colorList[2]">
					<div class="text">立即点击报名</div>
				</div>

				<img :src="baseUrl+item" v-for="(item, index) in imagesList" :key="index" v-if="index > 0" />
			</div>
			<div class="footer">
				<div class="price">{{ produInfo.productPrice || 1 }}</div>
				<div class="text" @click="submitForm('form',1)">
					<div class="breathe">立即报名</div>
				</div>
			</div>
		</div>

		<!-- 支付结果查询 -->
		<div class="mask" v-if="showWxRes">
			<div class="panel panel2">
				<div class="df">
					<div class="btn left" @click="rePay">未支付</div>
					<div class="btn right" @click="reWechat">已支付,添加老师</div>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
	import axios from 'axios';
	import { getQueryVariable, clickThrottle } from '@/utils/index'

	var checkPhone = (rule, value, callback) => {
		const regPhone = /^1[3|4|5|6|7|8|9][0-9]{9}$/
		if (value === '') {
			return callback(new Error('手机号不能为空'))
		} else if (!regPhone.test(value)) {
			callback(new Error('请输入正确的手机号'))
		} else {
			callback()
		}
	};

	export default {
		data () {
			return {
				productId:1,
				produInfo:{},//产品信息
				imagesList:[],//图片
				colorList:[],//主题色
				baseUrl:`${this.$siteURL}/imgs/mini/`,
				openId: localStorage.getItem('openId') || '',
				pathId:'',//投放平台pathid
				timer:false,
				count: 60,
				showText:'',
				showError:false,
				form: {
					code:'',
					mobile: ''
				},
				rules: {
					code:[{ required: true, message: '请输入验证码', trigger: 'blur' }],
					mobile: [
						{ required: true, message: '请输入手机号', trigger: 'blur' },
						{ validator: checkPhone, trigger: 'blur' }
					]
				},
				phoneLcok:false,//手机输入埋点
				smsLock:false,
				wxPoll: null,
				showWxRes: false,
				loading:true
			}
		},
		created(){
			this.form.mobile = this.form.mobile || this.$store.state.userPhone || ''
			this.productId = this.$route.query.productId || 1   //产品ID
			this.checkWX()
		},
		methods:{
			checkWX(){
				var ua = navigator.userAgent.toLowerCase();
				var isWeixin = ua.indexOf('micromessenger') != -1;
				//非微信浏览器提示
				if (!isWeixin) {
					document.head.innerHTML = '<title>抱歉，出错了</title><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=0"><link rel="stylesheet" type="text/css" href="https://res.wx.qq.com/open/libs/weui/0.4.1/weui.css">';
					document.body.innerHTML = '<div class="weui_msg"><div class="weui_icon_area"><i class="weui_icon_info weui_icon_msg"></i></div><div class="weui_text_area"><h4 class="weui_msg_title">请在微信客户端打开链接</h4></div></div>';
				}else{
					let code = getQueryVariable("code")
					this.getProduct()
					if(code){
						this.getOpenID(code)
						this.getPathid()
					}else{
						this.getAuthCode()
					}
				}
			},
			//获取微信静默授权-code
			getAuthCode(){
                let localPath = window.location.href
                let newPath = encodeURIComponent(localPath)
				let url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx2238825427205438&redirect_uri="+newPath+"&response_type=code&scope=snsapi_base#wechat_redirect"
				window.location.replace(url)
			},
			//获取微信授权-openID
			getOpenID(code){
				axios({
					method:"GET",
					url:`${this.$baseURL}/getAccessToken`,
					params:{
						code: code
					}
				}).then(res => {
					if(res.data.code == 200){
						this.openId = res.data.data.openid
					}else{
						this.$message({
							message: '系统繁忙，请刷新页面重试',
							type: 'warning'
						})
					}
				})
			},
			// 优酷入库-获取pathid
			getPathid(){
				let path = encodeURIComponent(window.location.href)
				axios({
					method:"GET",
					url:`${this.$baseURL}/getUKcpm`,
					params:{
						putIndex: path
					}
				}).then(res => {
					this.pathId = res.data.message
				})
			},
      		getProduct(){
				axios({
					method:'GET',
					url: `${this.$baseURL}/queryProductInfo`,
					params:{
						productId: this.productId
					}
				}).then(res => {
					this.loading = false
					this.produInfo = res.data
					this.imagesList = res.data.images
					this.colorList = res.data.theme && res.data.theme.indexOf(',') > 0 ? res.data.theme.split(',') : ['#fff','#1ACE9A','#1ACE9A']
				})
			},
			handlePhone(val){  
				if(val.length > 6){
					if(this.phoneLcok){
						return false
					}
					this.phoneLcok  = true
					let that = this
					setTimeout(() => {
						that.phoneLcok  = false
						that.doPoint('ecEnterPhone',0)//埋点
					},2000)
				}else{
					this.phoneLcok  = false
				}
			},
			handleSms(val){
				this.form.code = val.slice(-6)
				if(this.smsLock){
					return
				}
				this.smsLock = true
				this.doPoint('ecEnterCode',0)//埋点
			},
			//获取短信验证码
			getCode(){
				if(!this.form.mobile){
					this.showError = true
					this.showText = '请输入手机号'
					return false
				}
				const regPhone = /^1[3|4|5|6|7|8|9][0-9]{9}$/
				if(!regPhone.test(this.form.mobile)){
					this.showError = true
					this.showText = '请输入正确的手机号'
					return false
				}
				this.showError = false

				this.doPoint('ecGetCode',0)//埋点
				axios({
					method:"GET",
					url:`${this.$baseURL}/sms`,
					params:{
						phone: this.form.mobile
					}
				}).then(res => {
					if(res.data.code == 0){
						this.countDown()
					}else{
						this.$message({
							message: res.data.msg,
							type: 'warning'
						})
					}
				})
			},
			//短信定时器
			countDown(){
				if(this.count > 0){
					this.timer = true
					setTimeout(() => {
						this.count--
						this.countDown()
					},1000)
				}else{
					this.timer = false
					this.count = 60
				}
			},
			submitForm(formName,val) {
				this.showError = false
				this.$refs[formName].validate((valid) => {
					if (valid) {
						if(!clickThrottle(2000)) return
						this.doPoint('ecApplyNow',val)
						this.login()
					} else {
						window.scrollTo({
							top:150,
							behavior:'smooth'
						})
						return false
					}
				});
			},
			login(){
				axios({
					method:"POST",
					url:`${this.$baseURL}/userLoginSmsVerify`,
					params:{
						userPhone: this.form.mobile,
						code: this.form.code,
						productId: this.productId,
						pathId: this.pathId
					}
				}).then(res => {
					if(res.data.code == 200){
						this.doPoint('ecUpPayment',0)
						this.$store.commit("SET_PHONE", this.form.mobile)
						this.wechatPay()
					}else if(res.data.code == 1004){
						this.wechatOpen(0,1)
					}else{
						this.$message({message: res.data.message});
					}
				})
			},
			//支付弹窗-未支付
			rePay(){
				this.showWxRes = false
				this.doPoint('ecNonPayment',0)
				clearInterval(that.wxPoll)
			},
			//支付弹窗-已支付
			reWechat(){
				this.wechatOpen(1,1)
				this.doPoint('ecNonPayment',1)
			},
			wechatPay(){
				let num = (this.produInfo.productPrice * 100).toFixed(0)
				// let that = this
				// setTimeout(() => {
				// 	that.showWxRes = true
				// },2500)
				axios({
					method:"POST",
					url:`${this.$baseURL}/v3/jsapi/prePay`,
					params: {
						openid: this.openId,
						pathId: this.pathId,
						userPhone: this.form.mobile,
						productId: this.productId,
						productName: this.produInfo.productName,
						price: num
					}
				}).then(res => {
					if(res.data.data.code == 200){
						this.wxPrePay(res.data.data.data)
					}else{
						let msg = res.data.data.msg || res.data.msg
						this.$message({message: msg})
					}
				})
			},
			//微信支付
			wxPrePay(param){
				let that = this
				WeixinJSBridge.invoke('getBrandWCPayRequest', {
					"appId": param.appId,				//公众号ID，由商户传入     
					"timeStamp": param.timeStamp,     	//时间戳，自1970年以来的秒数     
					"nonceStr": param.nonceStr,      	//随机串     
					"package": param.packageVal,
					"signType":  param.signType,		//微信签名方式RSA
					"paySign": param.paySign 			//微信签名 
				},
				function(res) {
					//res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
					if (res.err_msg == "get_brand_wcpay_request:ok") {
						that.wxPolling()
						setTimeout(() => {
							clearInterval(that.wxPoll)
						},180000)
					}
				});
			},
			wxPolling(){
				this.wxPoll = setInterval(() => {
					this.wechatOpen(1,0)
				},1000)
			},
			//打开获客链接 type=0,不下发短信;type=1,下发短信。showMsg=0,不展示信息，showMsg=1展示信息
			wechatOpen(type,showMsg){
				axios({
					method:"POST",
					url:`${this.$baseURL}/getWechatIndexClass`,
					params: {
						userPhone: this.form.mobile
					}
				}).then(res => {
					if(res.data.code == 200){
						clearInterval(this.wxPoll)
						let data = res.data.data
						if(type == 1){
							this.custSms(data.class_wechat_index,data.class_id,data.class_user_id)
						}else{
							window.location.href = data.class_wechat_index + '?customer_channel=' + data.class_id + '_H5' + '_' + this.productId
						}
					}else{
						if(showMsg == 1){
							this.$message({message: '支付失败或未查到支付结果'});
						}
					}
				})
			},
			//下发客户短信
			custSms(url,id,wx){
				axios({
					method:"POST",
					url:`${this.$backend}/customer_acquisition/send_signup_sms`,
					data: {
						"class_id": id,
    					"wx_user_id":wx
					}
				}).then(res => {
					window.location.href = url + '?customer_channel=' + id + '_H5' + '_' + this.productId
				})
			},
			//埋点
			doPoint(type,val){
				let params = {
					clickId: this.pathId,
					productId: this.productId,
					[type] : val
				}
				axios({
					method:"POST",
					url:`${this.$baseURL}/insertApplyEc`,
					params: params
				}).then(res => {
					if(res.data.code !== 200){
						console.log(res.data.message)
					}
				})
			},
		}
	}
</script>


<style scoped>
	.footer{background-image: url('./../assets/images/btn2.png');}
	.price{color: #ff4242;position: absolute;left: 20px;bottom: 8px;font-size: 42px;font-weight: bold;}

	.pay-type{display: flex;justify-content: space-around;}
	.pay-type .item{text-align: center;background: #F2F2F2;font-size: 18px;color: #333;;width: 35%;padding: 15px;border-radius: 10px;border: 1px solid #F2F2F2;}
	.pay-type .item.on{background: #F6E5E5;border-color: #FF0000;}
	.pay-type .item img{width: 35px;height: 35px;}
	.el-button.is-round{width: 100%;background: linear-gradient(90deg, #ff4242 0%, #ff7e18 100%);border: none;color: #fff;font-size: 20px;}
	
	.panel{background: url(../assets/images/retain.png) no-repeat;width: 100%;height: 82vw;background-size: cover;    margin-top: 40%;position: relative;}
	.panel .df{position: absolute;bottom: 0;left: 0;right: 0;justify-content: center;}
	.panel .btn{padding: 10px 20px;border-radius: 10px;margin: 20px 15px 40px;font-size: 20px;font-weight: bold;}
	.panel .left{color: #7D2500;border: 1px solid #7D2500;}
	.panel .right{color: #fff;background: linear-gradient(90deg, #FF0000 0%, #FF7200 100%);}

	.panel2{background-image: url(../assets/images/pay.png);border-radius: 20px;width: calc(100% - 30px);height: 96vw;margin-left: auto;margin-right: auto;max-height: 666px;max-width: 641px;}
	.panel2 .btn{padding: 10px;margin: 20px 10px;font-weight: normal;}

	.cbtn{margin: 20px 30px 0px;padding: 18px 25px;background: #1ACE9A;text-align: center;border-radius: 35px;margin-bottom: 20px;}
	.cbtn .text{animation: testAnimation 1.5s linear infinite;color: #fff;font-size: 1.5rem;letter-spacing: 2px;font-weight: bold;cursor: pointer;}
	/* css3 */
	@keyframes testAnimation {
		0%{
			transform: scale(.9);
		}
		50%{
			transform: scale(1.2);
		}
		100%{
			transform: scale(.9);
		}
	}

	@media screen and (min-width:740px){
		.price{font-size: 90px;bottom:15px;}
	}
</style>
